﻿using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.Model.DataModel.SysCommon;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace LdtJudge.DataEngine.Data
{
    /// <summary>
    /// 案由实体提取类
    /// </summary>
    public class DALSYS_CaseCause
    {
        private static string connsys = ConfigRetrieval.GetConfigRetrieval.GetConnectionString("Ldt_JudgeDocSystem");
        private static SqlHandle sqhandle;

        #region 案由类相关操作

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="connectionstring"></param>

        public DALSYS_CaseCause()
        {
            if (string.IsNullOrWhiteSpace(connsys))
            {
                connsys = connsys;
            }
            sqhandle = new SqlHandle(connsys);
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public CaseCauseModel GetModelByCauseName(string ccName, string caseType)
        {
            string caseTypee = ReturnCaseType(caseType);
            caseType = caseTypee;
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from SYS_CaseCause ");
            strSql.Append(" where (CC_Name=@CC_Name or CC_ID=@CC_Name) and CC_NodeType=2");
            if (!string.IsNullOrEmpty(caseType))
            {
                strSql.Append(" AND CHARINDEX('" + caseType + "',AllParentId)>0 ");
            }
            IDbCommand dbCommand = sqhandle.GetSqlHelper.GetCommand(strSql.ToString());
            sqhandle.GetSqlHelper.AddInParameter(dbCommand, "@CC_Name", DbType.String, ccName);
            CaseCauseModel model = null;
            model = ReaderBind(sqhandle.GetSqlHelper.ExecuteReader(dbCommand).Rows[0]);

            return model;
        }
        /// <summary>
        /// 得到一个案由实体
        /// </summary>
        /// <param name="CC_ID"></param>
        /// <returns></returns>
        public CaseCauseModel GetModel(string CC_ID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from SYS_CaseCause ");
            strSql.Append(" where CC_ID=@CC_ID ");
            CaseCauseModel model = null;
            IDbCommand dbCommand = sqhandle.GetSqlHelper.GetCommand(strSql.ToString());
            sqhandle.GetSqlHelper.AddInParameter(dbCommand, "@CC_ID", DbType.String, CC_ID);
            model=ReaderBind(sqhandle.GetSqlHelper.ExecuteReader(dbCommand).Rows[0]);
            return model;
        }

        /// <summary>
        /// 把查询到的数据Table转为强类型MSYS_CaseCause
        /// </summary>
        /// <param name="CauseID">案由ID</param>
        /// <returns></returns>
        public IList<CaseCauseModel> GetList_FactElement(string CauseID)
        {
            DataTable oTb = GetTable_FactElement(CauseID);

            var query = from DataRow item in oTb.Rows select DataRowToModel(item);
            return query.ToList<CaseCauseModel>();
        }

        /// <summary>
        /// 得到案由相关的事实要素XML配置
        /// </summary>
        /// <param name="CauseID"></param>
        /// <returns></returns>
        public DataTable GetTable_FactElement(string CauseID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from SYS_CaseCause where AllParentId like '%," + CauseID.ToString() + ",%' and CC_NodeType in (11,12) order by CC_GlobalOrder");
            IDbCommand dbCommand = sqhandle.GetSqlHelper.GetCommand(strSql.ToString());

            return sqhandle.GetSqlHelper.ExecuteReader(dbCommand);
        }
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public CaseCauseModel DataRowToModel(DataRow row)
        {
            CaseCauseModel model = new CaseCauseModel();
            if (row != null)
            {
                if (row["CC_ID"] != null)
                {
                    model.CC_ID = row["CC_ID"].ToString();
                }
                if (row["CC_Name"] != null)
                {
                    model.CC_Name = row["CC_Name"].ToString();
                }
                if (row["CC_Code"] != null)
                {
                    model.CC_Code = row["CC_Code"].ToString();
                }
                if (row["CC_ParentID"] != null)
                {
                    model.CC_ParentID = row["CC_ParentID"].ToString();
                }
                if (row["CC_OfficialCode"] != null)
                {
                    model.CC_OfficialCode = row["CC_OfficialCode"].ToString();
                }
                if (row["CC_EqualCode"] != null)
                {
                    model.CC_EqualCode = row["CC_EqualCode"].ToString();
                }
                if (row["CC_SerialNumb"] != null && row["CC_SerialNumb"].ToString() != "")
                {
                    model.CC_SerialNumb = decimal.Parse(row["CC_SerialNumb"].ToString());
                }
                if (row["CC_Explain"] != null)
                {
                    model.CC_Explain = row["CC_Explain"].ToString();
                }
                if (row["isSave"] != null && row["isSave"].ToString() != "")
                {
                    model.isSave = int.Parse(row["isSave"].ToString());
                }
                if (row["CC_NodeType"] != null && row["CC_NodeType"].ToString() != "")
                {
                    model.CC_NodeType = int.Parse(row["CC_NodeType"].ToString());
                }
                if (row["isLeafNode"] != null && row["isLeafNode"].ToString() != "")
                {
                    model.isLeafNode = int.Parse(row["isLeafNode"].ToString());
                }
                if (row["AllParentId"] != null)
                {
                    model.AllParentId = row["AllParentId"].ToString();
                }
                if (row["HW_level"] != null && row["HW_level"].ToString() != "")
                {
                    model.HW_level = int.Parse(row["HW_level"].ToString());
                }
                if (row["CC_RegexInfoCode"] != null)
                {
                    model.CC_RegexInfoCode = row["CC_RegexInfoCode"].ToString();
                }
                if (row["AllParentName"] != null)
                {
                    model.AllParentName = row["AllParentName"].ToString();
                }
                if (row["CC_InferRuleTextByCode"] != null)
                {
                    model.CC_InferRuleTextByCode = row["CC_InferRuleTextByCode"].ToString();
                }
                if (row["ElementXML"] != null)
                {
                    model.ElementXML = row["ElementXML"].ToString();
                }
                if (row["OptimizeXML"] != null)
                {
                    model.ElementXML = row["OptimizeXML"].ToString();
                }
                if (row["ConfigXML"] != null)
                {
                    model.ElementXML = row["ConfigXML"].ToString();
                }

                if (row["CC_IsDefineExtract"] != null && row["CC_IsDefineExtract"].ToString() != "")
                {
                    model.CC_IsDefineExtract = int.Parse(row["CC_IsDefineExtract"].ToString());
                }

                if (row["CC_DefineExtractType"] != null)
                {
                    model.CC_DefineExtractType = row["CC_DefineExtractType"].ToString();
                }
                if (row["CC_GlobalOrder"] != null)
                {
                    model.CC_GlobalOrder = row["CC_GlobalOrder"].ToString();
                }
                if (row["XmlPath"] != null)
                {
                    model.XmlPath = row["XmlPath"].ToString();
                }
            }
            return model;
        }
        /// <summary>
        /// 转换实体
        /// </summary>
        /// <param name="dataReader"></param>
        /// <returns></returns>
        public CaseCauseModel ReaderBind(DataRow dataReader)
        {
            CaseCauseModel model = new CaseCauseModel();
            object ojb;
            model.CC_ID = dataReader["CC_ID"].ToString();
            model.CC_Name = dataReader["CC_Name"].ToString();
            model.CC_Code = dataReader["CC_Code"].ToString();
            model.CC_ParentID = dataReader["CC_ParentID"].ToString();
            model.CC_OfficialCode = dataReader["CC_OfficialCode"].ToString();
            model.CC_EqualCode = dataReader["CC_EqualCode"].ToString();
            model.XmlPath = dataReader["XmlPath"].ToString();
            ojb = dataReader["CC_SerialNumb"];
            if (ojb != null && ojb != DBNull.Value)
            {
                model.CC_SerialNumb = (decimal)ojb;
            }
            model.CC_Explain = dataReader["CC_Explain"].ToString();
            ojb = dataReader["isSave"];
            if (ojb != null && ojb != DBNull.Value)
            {
                model.isSave = (int)ojb;
            }
            ojb = dataReader["CC_NodeType"];
            if (ojb != null && ojb != DBNull.Value)
            {
                model.CC_NodeType = (int)ojb;
            }
            ojb = dataReader["isLeafNode"];
            if (ojb != null && ojb != DBNull.Value)
            {
                model.isLeafNode = (int)ojb;
            }
            model.AllParentId = dataReader["AllParentId"].ToString();
            ojb = dataReader["HW_level"];
            if (ojb != null && ojb != DBNull.Value)
            {
                model.HW_level = (int)ojb;
            }
            model.CC_RegexInfoCode = dataReader["CC_RegexInfoCode"].ToString();
            model.AllParentName = dataReader["AllParentName"].ToString();
            model.CC_InferRuleTextByCode = dataReader["CC_InferRuleTextByCode"].ToString();
            model.ElementXML = dataReader["ElementXML"].ToString();
            model.OptimizeXML = dataReader["OptimizeXML"].ToString();
            model.ConfigXML = dataReader["ConfigXML"].ToString();
            ojb = dataReader["CC_IsDefineExtract"];
            if (ojb != null && ojb != DBNull.Value)
            {
                model.CC_IsDefineExtract = (int)ojb;
            }
            model.CC_DefineExtractType = dataReader["CC_DefineExtractType"].ToString();
            model.CC_GlobalOrder = dataReader["CC_GlobalOrder"].ToString();

            ojb = dataReader["CC_DevelopSchedule"];
            if (ojb != null && ojb != DBNull.Value)
            {
                model.CC_DevelopSchedule = (int)ojb;
            }
            return model;
        }


        /// <summary>
        /// 根据案件类型获取案件的类型编号
        /// Returns the type of the case.
        /// </summary>
        /// <param name="caseType">Type of the case.</param>
        /// <returns></returns>
        public static string ReturnCaseType(string caseType)
        {
            switch (caseType.ToLower().Trim())
            {
                case "a1":
                case "xs":
                case "a2":
                case "a3":
                    return "1000";
                case "b1":
                case "b2":
                case "b3":
                case "ms":
                    return "1477";
                case "c1":
                case "xz":
                case "c2":
                case "c3":
                    return "2329";
                case "zx":
                    return "2449";
            }
            return string.Empty;
        }

        public DataTable GetTable_System(string strSQL)
        {

            return sqhandle.GetSqlHelper.ExecuteReader(strSQL);
        }

        /// <summary>
        /// 如果案由获取为空，则进行根据内容进行重新获取案由
        /// </summary>
        /// <param name="textcentent">文本内容</param>
        /// <param name="caseType">案件类型</param>
        /// <returns></returns>
        public string GetCauseID(string textcentent, string caseType)
        {
            Dictionary<string, string> causeList = new Dictionary<string, string>();
            string sys_cause = string.Empty;
            string code = ReturnCaseType(caseType);
            string sqlstr = @"SELECT * from SYS_CaseCause where CHARINDEX('" + code + ",',AllParentId)>0  and CC_NodeType='2'";
            DataTable dt = GetTable_System(sqlstr);
            foreach (DataRow row in dt.Rows)
            {
                if (!string.IsNullOrWhiteSpace(Convert.ToString(row["KeyWords"])))
                {
                    sys_cause = GetArgumentValueByMatchWords(Convert.ToString(row["KeyWords"]), textcentent);
                }
                if (string.IsNullOrWhiteSpace(sys_cause))
                {
                    bool Ismatch = System.Text.RegularExpressions.Regex.IsMatch(textcentent, "^.*?" + row["CC_Name"] + "|[一案]$");
                    if (Ismatch)
                    {
                        causeList.Add(Convert.ToString(row["AllParentId"]), Convert.ToString(row["CC_ID"]));
                    }
                }
            }
            if (string.IsNullOrWhiteSpace(sys_cause))
            {
                string causecodet = string.Empty;
                foreach (var value in causeList)
                {
                    if (value.Key.Contains(causecodet) || string.IsNullOrWhiteSpace(causecodet))
                    {
                        causecodet = value.Key;
                        sys_cause = value.Value;
                    }
                }
            }
            return sys_cause;
        }

        /// <summary>
        /// 根据匹配内容获取参数值
        /// </summary>
        /// <param name="matchKeyWords">匹配内容</param>
        /// <param name="originalValue">原始值</param>
        /// <returns>参数值</returns>
        public static string GetArgumentValueByMatchWords(string matchKeyWords, string originalValue)
        {
            string fieldValue = originalValue;
            matchKeyWords = Regex.Replace(matchKeyWords, @"(?<=;)\s", "", RegexOptions.Singleline);
            if (matchKeyWords != string.Empty)
            {
                fieldValue = (fieldValue == string.Empty) ? "空" : fieldValue;
                //string paternStr = RegexParseClass.GetRegexLastStr("DictMatchingA1");
                string paternStr = @"(?<=^|；|;)[^=]+(?==(?:[^=；;]*[,，]*?)(?<![\u4E00-\u9FFF\r，、]){MatchKeyWord}[,;；])";
                string currPatern = paternStr.Replace("{MatchKeyWord}", fieldValue);
                string extractValue = Regex.Match(matchKeyWords.Replace("\r", ""), currPatern, RegexOptions.Singleline).Value.Trim(); //返回匹配到的编号值！
                if (extractValue == string.Empty && fieldValue != "空")
                {
                    //01.假如当前匹配值，满足1）未匹配成功。2）本身就是匹配字典值中的一个。则直接返回。
                    if (Regex.IsMatch(matchKeyWords, @"(?:^|;)" + originalValue + "="))
                    {
                        return originalValue;
                    }
                    //02.上述没匹配成功，则再进行其他匹配。
                    currPatern = paternStr.Replace("{MatchKeyWord}", "其他");
                    extractValue = Regex.Match(matchKeyWords, currPatern, RegexOptions.Singleline).Value;    //返回匹配到的编号值！
                    extractValue = extractValue.Replace("\r", "");//2017-09-12 ljx 添加提取出来的结果存在 ”\r\r\r内容“这样的类型值
                }
                if (extractValue == string.Empty)
                {
                    return "";
                }
                else
                {
                    return extractValue;
                }
            }
            return originalValue;
        }

        #endregion

        #region 获取案件案由正则编号
        /// <summary>
        /// 根据民事文书类型获取民事案件案由提取的正则编号
        /// </summary>
        /// <param name="docID">文书类型</param>
        /// <returns></returns>
        public string GetBRelatRegexInfoCode(string docID)
        {
            string sqlstr = @"SELECT * FROM Dic_TableColumn_Priority";
            sqlstr += " where Col_ID in ( SELECT Col_ID from Dic_TableColumn  where tbl_id in ( select Tbl_ID from Dic_Table where Tbl_Name='CS_CaseCauseRelation'))";
            sqlstr += " and ( Col_Name='CH_CaseCauseName') and PT_Source ='"+ docID + "'";
            DataTable dt = GetTable_System(sqlstr);
            if (dt.Rows.Count == 0)
            {
                return null;
            }
            else
            {
                DataRow dr = dt.Rows[0];
                return Convert.ToString(dr["PT_RelatRegexInfoCode"]);
            }
        }

        /// <summary>
        /// 根据刑事文书类型获取刑事案件案由提取的正则编号
        /// </summary>
        /// <param name="docID"></param>
        /// <returns></returns>
        public string GetARelatRegexInfoCode(string docID)
        {
              
            string sqlstr = @"SELECT * FROM Dic_TableColumn_Priority";
            sqlstr += " where Col_ID in (SELECT Col_ID from Dic_TableColumn where tbl_id in (select Tbl_ID from Dic_Table where Tbl_Name = 'CS_SuitPart_Legation'))";
            sqlstr += " and(Col_Name = 'LT_CrimeNameID') and PT_Source = '" + docID + "'";
            DataTable dt = GetTable_System(sqlstr);
            if (dt.Rows.Count == 0)
            {
                return null;
            }
            else
            {
                DataRow dr = dt.Rows[0];
                return Convert.ToString(dr["PT_RelatRegexInfoCode"]);
            }
        }
        #endregion

        #region 获取配置信息
        /// <summary>
        /// 得到System数据表中，相关的行数据。
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="fkField">外键字段</param>
        /// <param name="fkValue">外键值</param>
        /// <returns>DataTable</returns>
        public  DataTable GetTable_System(string TableName, string fkField, string fkValue)
        {
            string strsql = "select * from " + TableName + " Where " + fkField + " ='"+fkValue+"'";

            IDbCommand dbCommand = sqhandle.GetSqlHelper.GetCommand(strsql.ToString());

            return sqhandle.GetSqlHelper.ExecuteReader(dbCommand);
        }
        #endregion

        /// <summary>
        /// 获取对应的
        /// </summary>
        /// <param name="causeid"></param>
        /// <param name="Sourcename"></param>
        /// <param name="ParagraphCode"></param>
        /// <returns></returns>
        public DataTable GetArgumentTabel(string causeid, string Sourcename, string ParagraphCode) 
        {
            string strsql = @"SELECT
	                                            b.CC_Name,
	                                            [ES_ID],
	                                            b.[CC_ID],
	                                            [Source_ID],
	                                            [Source_ParagraphID],
	                                            [Source_Name],
	                                            [Source_ParagraphName],
	                                            t.[CC_RegexInfoCode],
	                                            [IsParagraphExtract],
	                                            [IsEvidenceMatch]
                                            FROM
	                                            Ldt_JudgeDocSystem.dbo.[SYS_Express_Source] t
                                            LEFT JOIN Ldt_JudgeDocSystem.dbo.SYS_CaseCause b ON t.CC_ID = b.CC_ID
                                            WHERE 
                                                b.CC_NodeType=16 AND
	                                            t.Source_ID = '" + Sourcename + "' AND t.Source_ParagraphID = '" + ParagraphCode + "' AND b.AllParentId LIKE '%," + causeid + ",%'";

            IDbCommand dbCommand = sqhandle.GetSqlHelper.GetCommand(strsql.ToString());
            return sqhandle.GetSqlHelper.ExecuteReader(dbCommand);
        }
    }
}
